<template>
  <div class="box">
    <h1>登录页面</h1>
    <div>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="form"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="账号" prop="userName">
          <el-input v-model="form.userName" />
        </el-form-item>
        <el-form-item label="密码" prop="userPass">
          <el-input v-model="form.userPass" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
const router = useRouter();
import { login } from "@/api/api";
import { useRouter } from "vue-router";
const form = ref({
  userName: null,
  userPass: null,
});

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  userName: [{ required: true, message: "请输入账号", trigger: "blur" }],
  userPass: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      login(form.value).then((res) => {
        if (res.status == 200) {
          window.localStorage.setItem("token", res.data.data.token);
          window.localStorage.setItem(
            "user",
            JSON.stringify(res.data.data.user)
          );
          router.push("/home");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>

<style scoped></style>
